﻿using Common.Algorithm;
using Common.MefHelp;
using Common.Tools;
using Microsoft.AspNetCore.Http;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Responses;
using Ocelot.Values;

namespace Common.CustomLoadBalancer
{
    /// <summary>
    /// 最佳资源负载均衡
    /// </summary>
    public class BestResourcesLoadBalancer : ILoadBalancer
    {
        private readonly Func<Task<List<Service>>> _services;
        /// <summary>
        /// consul里面的所有服务会通过构造函数注入进来
        /// </summary>
        /// <param name="services"></param>
        public BestResourcesLoadBalancer(Func<Task<List<Service>>> services)
        {
            _services = services;
        }
        public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
        {
            var services = await _services.Invoke() ?? new List<Service>();
            if (services.Count > 0)
            {
                var model = await Mef.GetService<BestResources>().GetHost(services.Select(g => new IpAndPort
                {
                    Port = g.HostAndPort.DownstreamPort,
                    Ip = g.HostAndPort.DownstreamHost,
                }).ToList());
                ServiceHostAndPort result;
                if (model == null)
                {
                    LogHelper.Error($"获取自定义负载均衡机器为空");
                    result = services.First().HostAndPort;
                }
                else
                {
                    result = services.FirstOrDefault(x =>
                    x.HostAndPort.DownstreamHost == model.Ip && x.HostAndPort.DownstreamPort == model.Port)?.HostAndPort
                    ?? new ServiceHostAndPort(model.Ip, model.Port);

                }
                return new OkResponse<ServiceHostAndPort>(result);
            }
            return new ErrorResponse<ServiceHostAndPort>(new ServicesAreEmptyError($"There were no services in {nameof(BestResourcesLoadBalancer)} during {nameof(Lease)} operation."));

        }

        public void Release(ServiceHostAndPort hostAndPort)
        {

        }
    }
}
